#include "GameButton.h"
#include "MyRender.h"
#include "MyInputMgr.h"
#include "ConsoleWnd.h"

extern CMyRender g_kRender;
extern CMyInputMgr g_kInputMgr;
extern CConsoleWnd g_kConsoleWnd;

CGameButton::CGameButton(void)
{
	m_eWndType = WT_BUTTON;
}

CGameButton::~CGameButton(void)
{
}

bool CGameButton::OnLeftBtnDown( int iX,int iY )
{
	if (IsDisable())
	{
		return true;
	}

	m_spkLockControl = this;
	if (m_pkParent)
	{
		m_pkParent->ProcChildMsg(CM_LBtnDown,m_kName,m_kUserData);
	}

	return true;
}

bool CGameButton::OnLeftBtnUp( int iX,int iY )
{
	if (IsDisable())
	{
		return true;
	}

	if (m_pkParent)
	{
		m_pkParent->ProcChildMsg(CM_LBtnUp,m_kName,m_kUserData);
	}

	if (m_spkLockControl == this)
	{
		if (m_pkParent)
		{
			m_pkParent->ProcChildMsg(CM_Click,m_kName,m_kUserData);

			g_kConsoleWnd.PrintFormatLog("Btn[%s] Clicked %d",m_kName.c_str(),GetTickCount());
		}
	}

	m_spkLockControl = NULL;
	return true;
}

void CGameButton::OnDraw()
{
	CMyImage* pkImage = &m_kImageNormal;	

	if (m_spkMouseOnControl == this)
	{
		pkImage = &m_kImageFocus;
	}

	if (m_spkMouseOnControl == this && g_kInputMgr.IsLeftBtnDown())
	{
		pkImage = &m_kImageClick;
	}

	if (IsDisable())
	{
		pkImage = &m_kImageDisable;
	}

	g_kRender.DrawImage(*pkImage,m_iAbsX,m_iAbsY,m_iWidth,m_iHeight,(m_iAlpha << 24) | 0x00FFFFFF);

	int iTextWidth = GetTextSize(m_kText.c_str(),m_dwFontInfo).cx;
	int iTextHeight = GetTextSize(m_kText.c_str(),m_dwFontInfo).cy;

	g_kRender.DrawText(m_kText.c_str(),m_iAbsX + (m_iWidth - iTextWidth) / 2,m_iAbsY + (m_iHeight - iTextHeight) / 2,m_dwTextColor);
}

void CGameButton::LoadResFromFile( const string& rkFile )
{
	CMyImage kImage;
	kImage.Load(rkFile);

	LoadResFormImage(kImage);
	return;
}

void CGameButton::LoadResFromDir( const string& rkDir )
{
	m_kImageNormal.Load(rkDir + "/" + "normal.bmp");
	m_kImageFocus.Load(rkDir + "/" + "focus.bmp");
	m_kImageClick.Load(rkDir + "/" + "click.bmp");
	m_kImageDisable.Load(rkDir + "/" + "disable.bmp");
	return;
}

void CGameButton::LoadResFormImage( const CMyImage& rkImage )
{
	int iWidth = rkImage.GetWidth() / 4;
	int iHeight = rkImage.GetHeight();
	m_kImageNormal.LoadFromImage(rkImage,0,0,iWidth,iHeight);
	m_kImageFocus.LoadFromImage(rkImage,iWidth,0,iWidth,iHeight);
	m_kImageClick.LoadFromImage(rkImage,iWidth * 2,0,iWidth,iHeight);
	m_kImageDisable.LoadFromImage(rkImage,iWidth * 3,0,iWidth,iHeight);

	return;
}
